package com.rednose.videoplayer.activities;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.rednose.videoplayer.R;
import com.rednose.videoplayer.utils.Utility;
import com.rednose.videoplayer.controller.*;

public class RegisterActivity extends AppCompatActivity {

    private EditText usernameEditText;
    private EditText passwordEditText,againPasswordEditText;
    private Button registerButton;

    private RegisterController registerController;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        usernameEditText = findViewById(R.id.regUsernameEditText);
        passwordEditText = findViewById(R.id.regPasswordEditText);
        againPasswordEditText = findViewById(R.id.againPasswordEditText);
        registerButton = findViewById(R.id.registerButton);


        registerController = new RegisterController(this);

        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = usernameEditText.getText().toString();
                String password = passwordEditText.getText().toString();
                String againPassword = againPasswordEditText.getText().toString();
                String passwordHash = Utility.hashPassword(password);

                if(!password.equals(againPassword)){
                    Toast.makeText(RegisterActivity.this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (registerController.register(username, passwordHash)) {
                    Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                    // 跳转到登录活动
                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                    startActivity(intent);startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(RegisterActivity.this, "注册失败，用户名可能已存在", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}